<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option label="处理中" :value="0" />
          <el-option label="已发货" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['point:order:add']">新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['point:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['point:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['point:order:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="forceRefresh">强制刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="用户名称" align="center" prop="users.nickname" />
      <el-table-column label="商品名称" align="center" prop="mallGoods.name" />
      <el-table-column label="消耗积分" align="center" prop="point" />
      <el-table-column label="收货地址" align="center" prop="userAddress.address" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['point:order:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['point:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="商品ID" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="消耗积分" prop="point">
          <el-input v-model="form.point" placeholder="请输入消耗积分" />
        </el-form-item>
        <el-form-item label="地址ID" prop="addressId">
          <el-input v-model="form.addressId" placeholder="请输入地址ID" />
        </el-form-item>
<!--        <el-form-item label="订单状态" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio :label="0">处理中</el-radio>-->
<!--            <el-radio :label="1">已发货</el-radio>-->
<!--            <el-radio :label="2">已完成</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="debugFormData">调试数据</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/point/order"
import request from "@/utils/request"

export default {
  name: "Order",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      orderList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        status: null
      },
      form: {},
      rules: {
        orderSn: [{ required: true, message: "订单编号不能为空", trigger: "blur" }],
        userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }],
        goodsId: [{ required: true, message: "商品ID不能为空", trigger: "blur" }],
        goodsName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        point: [{ required: true, message: "消耗积分不能为空", trigger: "blur" }],
        addressId: [{ required: true, message: "地址ID不能为空", trigger: "blur" }],
        status: [{ required: true, message: "订单状态不能为空", trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      request({
        url: '/point/order/all-details',
        method: 'get'
      }).then(response => {
        if (response.code === 200) {
          let allData = response.data || []
          if (this.queryParams.goodsName) {
            allData = allData.filter(item => item.mallGoods && item.mallGoods.name && item.mallGoods.name.includes(this.queryParams.goodsName))
          }
          if (this.queryParams.status !== null && this.queryParams.status !== '') {
            allData = allData.filter(item => item.status === this.queryParams.status)
          }
          this.total = allData.length
          const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
          const end = start + this.queryParams.pageSize
          this.orderList = allData.slice(start, end)
        } else {
          this.$modal.msgError(response.msg || "获取数据失败")
        }
        this.loading = false
      }).catch(error => {
        console.error('获取订单数据失败:', error)
        this.$modal.msgError("获取订单数据失败")
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        orderSn: null,
        userId: null,
        goodsId: null,
        goodsName: null,
        point: null,
        addressId: null,
        status: 0,
        createTime: null,
        updateTime: null,
        del: 0
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        status: null
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加积分兑换订单"
    },
    handleUpdate(row) {
      const id = row.id || this.ids
      request({
        url: `/point/order/detail/${id}`,
        method: 'get'
      }).then(response => {
        if (response.code === 200) {
          this.reset()
          this.form = {
            id: Number(response.data.id),
            orderSn: response.data.orderSn,
            userId: Number(response.data.userId),
            goodsId: Number(response.data.goodsId),
            goodsName: response.data.goodsName,
            point: Number(response.data.point),
            addressId: response.data.addressId ? Number(response.data.addressId) : null,
            status: Number(response.data.status),
            createTime: response.data.createTime,
            updateTime: response.data.updateTime,
            del: Number(response.data.del)
          }
          this.open = true
          this.title = "修改积分兑换订单"
        } else {
          this.$modal.msgError(response.msg || "获取订单详情失败")
        }
      }).catch(error => {
        console.error('获取订单详情失败:', error)
        this.$modal.msgError("获取订单详情失败")
      })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            const updateData = {
              id: this.form.id,
              orderSn: this.form.orderSn,
              userId: this.form.userId,
              goodsId: this.form.goodsId,
              goodsName: this.form.goodsName,
              point: this.form.point,
              addressId: this.form.addressId,
              status: this.form.status
            }
            updateOrder(updateData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.queryParams.status = null
                this.queryParams.goodsName = null
                this.queryParams.pageNum = 1
                this.getList()
                setTimeout(() => {
                  this.getList()
                }, 1000)
              } else {
                this.$modal.msgError(response.msg || "修改失败")
              }
            }).catch(error => {
              console.error('更新失败:', error)
              this.$modal.msgError("修改失败")
            })
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除积分兑换订单编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    handleExport() {
      this.download('point/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    getStatusType(status) {
      if (status === 0) return 'info'
      if (status === 1) return 'success'
      if (status === 2) return 'warning'
      return ''
    },
    getStatusText(status) {
      if (status === 0) return '处理中'
      if (status === 1) return '已发货'
      if (status === 2) return '已完成'
      return ''
    },
    debugFormData() {
      console.log('当前表单数据:', this.form)
      console.log('当前表格数据:', this.orderList)
      this.$modal.msgSuccess('当前表单和表格数据已打印到控制台')
    },
    forceRefresh() {
      this.getList()
    }
  }
}
</script>
